package com.uottawa.library.controller;

import java.io.IOException;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Servlet Filter implementation class RequestLoggingFilter
 */
@WebFilter(filterName="/RequestLoggingFilter",  urlPatterns={"/*"})
public class LoginFilter implements Filter {
 
    private ServletContext context;
     
    public void init(FilterConfig fConfig) throws ServletException {
        this.context = fConfig.getServletContext();
    }
 
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        Object user = req.getSession().getAttribute("user");
        if(user == null && 
        		!(req.getServletPath().contains("index.jsp") || (req.getServletPath().contains("login")))) {
        	res.sendRedirect("index.jsp");
        	return;
        }
        // pass the request along the filter chain
        chain.doFilter(request, response);
    }
 
    public void destroy() {
        //we can close resources here
    }
 
}